//
//  FSWBaseWebViewController.m
//  quhuolang_driver
//
//  Created by 曹欣欣 on 2018/3/6.
//  Copyright © 2018年 fusw. All rights reserved.
//

#import "FSWBaseWebViewController.h"
#import <WebKit/WebKit.h>
#import "MainNavigationVC.h"
#import "FSWGetAppInfo.h"
#import "FSWForgetPwdCodeController.h"
@interface FSWBaseWebViewController ()<WKUIDelegate,WKNavigationDelegate,UIScrollViewDelegate,WKScriptMessageHandler>
 
@property (nonatomic, strong) WKWebView* webview;
@property (nonatomic,strong) CALayer *progresslayer;
@property (nonatomic, assign) BOOL isFinished;
@property (nonatomic, strong) CLLocationManager *locationMgr;
@property (assign, nonatomic) BOOL allowZoom;
@property (strong, nonatomic) NSString *urlString;
@end

@implementation FSWBaseWebViewController
- (IBAction)leftButton:(id)sender {
    
    if (self.webview.canGoBack) {
        [self.webview goBack];
    }else{
        [self pop];
    }
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [super viewWillAppear:animated];
    
    [fNotification addObserver:self selector:@selector(getNotificationResult:) name:@"message" object:nil];
    
    self.titleLabel.text = self.titleStr;
    self.navBackView.hidden = NO;
    float topHeight = [FSWHelperTool isFringe] ? 44 : 22;
    [self.view insertSubview:self.webview belowSubview:self.navBackView];
    switch (self.type) {
        case  0:
            //            [self.webview reload];
            [self.tabBarController.tabBar setHidden:NO];
//            self.topHeightLayout.constant = 44;
            self.leftButton.hidden = YES;
            self.webview.frame = CGRectMake(0, topHeight+44, SCREEN_WIDTH, self.view.xc_height -topHeight-44);
            break;
        case  1:
//            self.topHeightLayout.constant = 0;
            [self.tabBarController.tabBar setHidden:YES];
             self.webview.frame = CGRectMake(0, topHeight, SCREEN_WIDTH, SCREEN_HEIGHT-topHeight);
            
            break;
        case  2:
//            self.topHeightLayout.constant = 44;
            [self.tabBarController.tabBar setHidden:NO];
            self.leftButton.hidden = YES;
              self.webview.frame = CGRectMake(0, topHeight+44, SCREEN_WIDTH, self.view.xc_height -topHeight-44);
            break;
        case  10:
//            self.topHeightLayout.constant = 0;
            [self.tabBarController.tabBar setHidden:YES];
            self.navBackView.hidden = YES;
            self.leftButton.hidden = YES;
            self.webview.frame = CGRectMake(0, topHeight, SCREEN_WIDTH, self.view.xc_height -topHeight);
            break;
        default:
            [self.tabBarController.tabBar setHidden:YES];
            self.leftButton.hidden = NO;
//            self.topHeightLayout.constant = 0;
            self.webview.frame = CGRectMake(0, topHeight, SCREEN_WIDTH, self.view.xc_height -topHeight);
            break;
    }
    
 
    
}
-(void)webRequestLoad{
    if (self.webview) {
        NSURL *url = [NSURL URLWithString: self.urlStr];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [self.webview loadRequest:request];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //    [fNotification removeObserver:self name:@"message" object:nil];
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (!self.isFinished) {
        [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
    }
}

-(void)getNotificationResult:(NSNotification *)notification{
    NSDictionary *dict = notification.object;
    NSString *urlStr  = dict[@"url"];
    if (urlStr) {
        NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        [self.webview loadRequest:request];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //    if (@available(iOS 11.0, *)){
    //        //避免滚动视图顶部出现20的空白以及push或者pop的时候页面有一个上移或者下移的异常动画的问题
    //      self.webview.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    //    }else{
    //        self.edgesForExtendedLayout = UIRectEdgeNone;
    //    }
    [self setNavigationOrigin];
    //    self.view.backgroundColor = [UIColor colorWithHexString:@"2D3E4F"];
//    self.view.backgroundColor = XCMainColor;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.webview];
    self.webview.navigationDelegate = self;
    self.webview.scrollView.delegate = self;
    [self.webview.scrollView setZoomScale:0.8 animated:NO];
    [self configProgressUI];
       [self webRequestLoad];
    if (self.url) {
        NSString * jsonParam =[NSString stringWithFormat:@"{'adminuser':'fushengwen','adminpass':'123456'}"];
        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
        [request setHTTPMethod: @"POST"];
        [request setHTTPBody: [jsonParam dataUsingEncoding: NSUTF8StringEncoding]];
        [self.webview loadRequest:request];
    }
    //    // 获取JS所在的路径
    //    NSString *path = [[NSBundle mainBundle] pathForResource:@"JSPOST" ofType:@"html"];
    //    // 获得html内容
    //    NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //    [self.webview loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
    if (self.html) {
        [self.webview loadHTMLString:self.html baseURL:nil];
    }
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    // 禁止放大缩小
    NSString *injectionJSString;
    if ([self.urlString isEqualToString:@"http://oa.cf360.top/?m=index&d=we"]) {
        injectionJSString = @"var script = document.createElement('meta');"
        "script.name = 'viewport';"
        "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
        "document.getElementsByTagName('head')[0].appendChild(script);";
    }else{
        injectionJSString = @"var script = document.createElement('meta');"
        "script.name = 'viewport';"
        "script.content=\"width=device-width, height=device-height, initial-scale=1.0,maximum-scale=1.0, minimum-scale=0.1, user-scalable=yes\";"
        "document.getElementsByTagName('head')[0].appendChild(script);";
    }
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
    
    if ([FSWHelperTool stringRoaldSearch:self.urlString withString:@"login"]) {
        [webView evaluateJavaScript:@"FyOaApp()" completionHandler:nil];
    }
}

#pragma mark - Responder Method
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    @weakify(self)
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progresslayer.opacity = 1;
        if ([change[@"new"] floatValue] < [change[@"old"] floatValue]) return;
        self.progresslayer.frame = CGRectMake(0, 0, self.view.bounds.size.width * [change[@"new"] floatValue], 3);
        if ([change[@"new"] floatValue] == 1) {
            [self.webview removeObserver:self forKeyPath:@"estimatedProgress"];
            self.isFinished = YES;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                @strongify(self)
                self.progresslayer.opacity = 0;
            });
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                @strongify(self)
                self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
            });
        }
    }else if ([keyPath isEqualToString:@"title"]){
        if (!self.title) {
            //            self.title = _webview.title;
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - Delegate Method
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    self.urlString = [[navigationAction.request URL] absoluteString];
    self.urlString = [ self.urlString stringByRemovingPercentEncoding];
    if ([FSWHelperTool stringRoaldSearch:self.urlString withString:@"daka"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
//        FSWClockHomeController *NearbyVc = (FSWClockHomeController *)[self instantiateViewControllerWithStoryboardName:@"Home" identifier:@"FSWClockHomeController"];
//        MainNavigationVC* NearbyNavigation = [[MainNavigationVC alloc] initWithRootViewController:NearbyVc];
////        @weakify(self);
//        NearbyVc.block = ^{
////            @strongify(self);
//        };
//        NearbyNavigation.modalPresentationStyle = UIModalPresentationFullScreen;
//        [self presentViewController:NearbyNavigation animated:YES completion:nil];
    }
 
    else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
}


- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"showInfoFromJs"]) {
        //        [self pop];
        NSString *user_id = message.body;
        [fUserDefaults setObject:user_id forKey:JPUSH_USERNAME];
        [fUserDefaults setObject:user_id forKey:USER_ID];
        [self configJpush:user_id];
        NSString *registrationID = [NSString stringWithFormat:@"getRegistrationIdFromJpush('%@')",[JPUSHService registrationID]];
        [self.webview evaluateJavaScript:registrationID completionHandler:nil];
    }
    
    if ([message.name isEqualToString:@"delAliasFromJs"]) {
        //        [self pop];
        //        NSString *user_id = message.body;
        
        //        [fUserDefaults setObject:user_id forKey:JPUSH_USERNAME];
        [self configJpush:@""];
        //        NSString *registrationID = [NSString stringWithFormat:@"getRegistrationIdFromJpush('%@')",[JPUSHService registrationID]];
        //        [self.webview evaluateJavaScript:registrationID completionHandler:nil];
    }
    if ([message.name isEqualToString:@"backUserFromJs"]) {
        // 利用data参数处理自己的逻辑
        [self pop];
        if (self.webBackBlock) {
            self.webBackBlock();
        }
    }
    if ([message.name isEqualToString:@"backHomeFromJs"]) {
        // 利用data参数处理自己的逻辑
        if (self.webBackBlock) {
            self.webBackBlock();
        }
        [self pop];
    }
    
    if ([message.name isEqualToString:@"changeNewPassword"]) {
        // 利用data参数处理自己的逻辑
        FSWForgetPwdCodeController *vc = [self instantiateViewControllerWithStoryboardName:@"Login" identifier:@"FSWForgetPwdCodeController"];
        [self pushViewController:vc];
    }
}

#pragma mark - Private Method

#pragma mark - Setter/Getter
- (void)configProgressUI {
    UIView* progress = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 3)];
    progress.backgroundColor = [UIColor clearColor];
    [self.view addSubview:progress];
    
    self.progresslayer = [CALayer layer];
    self.progresslayer.frame = CGRectMake(0, 0, 0, 3);
    //    self.progresslayer.backgroundColor = [UIColor colorWithHexString:@"#1793FD"].CGColor;
    [progress.layer addSublayer:self.progresslayer];
}

- (WKWebView *)webview
{
    if (!_webview) {
        //以下代码适配大小
//        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        
        //        NSString *css = @"body{-webkit-user-select:none;-webkit-user-drag:none;}";
        NSMutableString *javascript = [NSMutableString string];
        [javascript appendString:@"var style = document.createElement('style');"];
        [javascript appendString:@"style.type = 'text/css';"];
        //        [javascript appendFormat:@"var cssContent = document.createTextNode('%@');", css];
        [javascript appendString:@"style.appendChild(cssContent);"];
        [javascript appendString:@"document.body.appendChild(style);"];
        // 禁用选中效果
        
        
        WKUserScript *noneSelectScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
        // js配置
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        [userContentController addScriptMessageHandler:self name:@"showInfoFromJs"];//返回
        [userContentController addScriptMessageHandler:self name:@"delAliasFromJs"];//返回
        [userContentController addScriptMessageHandler:self name:@"backUserFromJs"];//返回
        [userContentController addScriptMessageHandler:self name:@"backHomeFromJs"];//返回
        [userContentController addScriptMessageHandler:self name:@"changeNewPassword"];//返回
        [userContentController addUserScript:noneSelectScript];
        
        
        // WKWebView的配置
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = userContentController;
        
        configuration.preferences = [[WKPreferences alloc] init];
        configuration.preferences.javaScriptCanOpenWindowsAutomatically = YES;
        
        
        float topHeight = [FSWHelperTool isFringe] ? 44 : 22;
        
        
        _webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, topHeight, SCREEN_WIDTH, self.view.xc_height -topHeight ) configuration:configuration];
        _webview.allowsBackForwardNavigationGestures = YES;
        _webview.navigationDelegate = self;
        _webview.UIDelegate = self;
        
        [_webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        //         [[_webview configuration].userContentController addScriptMessageHandler:self name:@"showInfoFromJs"];
       
    }
    return _webview;
}
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)dealloc{
    //    [self.locationManager ]
}

//-(void)fromBrowser:(FSWUpdateVersionModel *)model{
//        NSString *openURL = @"http://pgyer.com/QfIU"; 
//    NSURL *URL = [NSURL URLWithString:openURL];
//    
//    /**
//     ios 9 之前使用
//     openURL:打开的网址
//     **/
////    [[UIApplication sharedApplication]openURL:URL];
//    
//    /**
//     ios 10 以后使用  openURL: options: completionHandler:
//     这个函数异步执行，但在主队列中调用 completionHandler 中的回调
//     openURL:打开的网址
//     options:用来校验url和applicationConfigure是否配置正确，是否可用。
//     唯一可用@{UIApplicationOpenURLOptionUniversalLinksOnly:@YES}。
//     不需要不能置nil，需@{}为置空。
//     ompletionHandler:如不需要可置nil
//     **/
//    if (@available(iOS 10.0, *)) {
//        [[UIApplication sharedApplication]openURL:URL options:@{} completionHandler:^(BOOL success) {
//            
//        }];
//    } else {
//        // Fallback on earlier versions
//    }
//}
@end


